// 文件名称: StudentManagementController.java
// 创建日期: 2023-10-05
// 描述: 学生管理控制器类，负责处理学生管理界面的各种操作。

package org.wisdom.studentchoose;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import org.wisdom.studentchoose.db.Student;
import org.wisdom.studentchoose.db.StudentDAO;

import java.io.IOException;
import java.util.List;

public class StudentManagementController {

    @FXML
    private ComboBox<String> classComboBox; // 班级下拉框

    @FXML
    private ComboBox<String> groupComboBox; // 小组下拉框

    @FXML
    private TextField addStudentNameField; // 添加学生姓名输入框

    @FXML
    private TextField addStudentNumberField; // 添加学生学号输入框

    @FXML
    private TextField addStudentMajorField; // 添加学生专业输入框

    @FXML
    private TextField addStudentGradeField; // 添加学生年级输入框

    @FXML
    private TextField deleteStudentNameField; // 删除学生姓名输入框

    @FXML
    private TableView<Student> studentList; // 学生列表表格

    @FXML
    private TableColumn<Student, Integer> studentIdColumn; // 学生ID列

    @FXML
    private TableColumn<Student, String> studentNameColumn; // 学生姓名列

    @FXML
    private TableColumn<Student, String> studentMajorColumn; // 学生专业列

    @FXML
    private TableColumn<Student, String> studentClassNameColumn; // 学生班级列

    @FXML
    private TableColumn<Student, String> studentGroupNameColumn; // 学生小组列

    @FXML
    private TableColumn<Student, String> studentNumberColumn; // 学生学号列

    @FXML
    private TableColumn<Student, Double> studentGradeColumn; // 学生成绩列

    @FXML
    private TableColumn<Student, String> studentGenderColumn; // 学生性别列

    private ObservableList<Student> students = FXCollections.observableArrayList(); // 学生列表

    @FXML
    public void initialize() {
        // 加载班级和小组数据
        loadClasses();
        loadGroups();

        // 当选择的班级发生变化时，重新加载对应的小组列表
        classComboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            loadGroups();
        });

        // 设置表格列的 cellValueFactory
        studentIdColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty().asObject());
        studentNameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        studentMajorColumn.setCellValueFactory(cellData -> cellData.getValue().majorProperty());
        studentClassNameColumn.setCellValueFactory(cellData -> cellData.getValue().classNameProperty());
        studentGroupNameColumn.setCellValueFactory(cellData -> cellData.getValue().groupNameProperty());
        studentNumberColumn.setCellValueFactory(cellData -> cellData.getValue().numberProperty());
        studentGradeColumn.setCellValueFactory(cellData -> cellData.getValue().gradeProperty().asObject());
//        studentGenderColumn.setCellValueFactory(cellData -> cellData.getValue().genderProperty());

        // 加载学生列表
        loadStudents();
    }

    private void loadClasses() {
        // 获取所有班级名称
        List<String> classes = StudentDAO.getClassNames();
        classComboBox.getItems().addAll(classes);
    }

    private void loadGroups() {
        // 清空当前的小组列表
        groupComboBox.getItems().clear();

        // 获取当前选中的班级名称
        String selectedClass = classComboBox.getValue();

        if (selectedClass != null && !selectedClass.isEmpty()) {
            // 获取对应班级的所有小组名称
            List<String> groups = StudentDAO.getGroupNames(selectedClass);
            groupComboBox.getItems().addAll(groups);
        }
    }

    private void loadStudents() {
        // 获取所有学生数据
        List<Student> allStudents = new StudentDAO().getAllStudents();
        System.out.println("Loaded students: " + allStudents.size());
        students.setAll(allStudents);
        studentList.setItems(students);
    }

    @FXML
    private void handleAddStudentButtonClick(ActionEvent event) {
        // 获取输入的学生信息
        String studentName = addStudentNameField.getText();
        String studentNumber = addStudentNumberField.getText();
        String selectedClass = classComboBox.getValue();
        String selectedGroup = groupComboBox.getValue();
        String studentMajor = addStudentMajorField.getText();
        String studentGradeStr = addStudentGradeField.getText();
        double studentGrade = 0.0;

        // 验证输入
        if (studentName == null || studentName.isEmpty() || studentNumber == null || studentNumber.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "请输入学生姓名和学号");
            alert.showAndWait();
            return;
        }

        if (selectedClass == null || selectedClass.isEmpty() || selectedGroup == null || selectedGroup.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "请选择一个班级和小组");
            alert.showAndWait();
            return;
        }

        if (studentGradeStr != null && !studentGradeStr.isEmpty()) {
            try {
                studentGrade = Double.parseDouble(studentGradeStr);
            } catch (NumberFormatException e) {
                Alert alert = new Alert(Alert.AlertType.ERROR, "成绩输入无效");
                alert.showAndWait();
                return;
            }
        }

        // 创建新学生对象
        Student newStudent = new Student(
                0, // ID 由数据库自动生成
                studentName,
                studentMajor,
                selectedClass,
                selectedGroup,
                studentNumber,
                studentGrade,
                "" // 性别默认为空
        );

        // 调用 DAO 方法添加学生
        new StudentDAO().addStudent(newStudent);

        // 重新加载学生列表
        loadStudents();

        // 清空输入框
        addStudentNameField.clear();
        addStudentNumberField.clear();
        addStudentMajorField.clear();
        addStudentGradeField.clear();
    }

    @FXML
    private void handleDeleteStudentButtonClick(ActionEvent event) {
        // 获取输入的学生信息
        String studentName = deleteStudentNameField.getText();
        String selectedClass = classComboBox.getValue();
        String selectedGroup = groupComboBox.getValue();

        // 验证输入
        if (studentName == null || studentName.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "请输入要删除的学生姓名");
            alert.showAndWait();
            return;
        }

        if (selectedClass == null || selectedClass.isEmpty() || selectedGroup == null || selectedGroup.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "请选择一个班级和小组");
            alert.showAndWait();
            return;
        }

        // 查找要删除的学生
        Student studentToRemove = students.stream()
                .filter(student -> student.getName().equals(studentName)
                        && student.getClassName().equals(selectedClass)
                        && student.getGroupName().equals(selectedGroup))
                .findFirst()
                .orElse(null);

        if (studentToRemove != null) {
            // 调用 DAO 方法删除学生
            new StudentDAO().deleteStudent(studentToRemove.getId());

            // 重新加载学生列表
            loadStudents();

            // 清空输入框
            deleteStudentNameField.clear();
        } else {
            Alert alert = new Alert(Alert.AlertType.ERROR, "未找到指定的学生");
            alert.showAndWait();
        }
    }

    @FXML
    private void handleBackButtonClick(ActionEvent event) {
        try {
            // 加载主菜单界面的 FXML 文件
            FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("menu-view.fxml"));
            Scene scene = new Scene(fxmlLoader.load(), 400, 300); // 设置主菜单界面的大小
            Stage stage = (Stage) ((Button) event.getSource()).getScene().getWindow();
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
